package org.example.new_hbps_backend_reconstruction.controller.patient;

/**
 * @author 丁利军
 * @date 2025年10月14日 13:03
 * @description 心永-二维码URL设置
 */


import com.alibaba.fastjson.JSONObject;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;

import org.example.new_hbps_backend_reconstruction.common.results.R;
import org.example.new_hbps_backend_reconstruction.utils.HTTPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

// --- OpenAPI / Swagger 相关 ---
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.parameters.RequestBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 心永-二维码URL设置
 * 文档：POST https://open.heart-forever.com/api/ext/qrUrl
 * 头：Content-Type: application/json; charset=utf-8
 *    access_token: {见4.1获取}
 * 体：{ "url": "https://open.heart-forever.com/gen_qr" }
 */
@Validated
@RestController
@RequestMapping("/ext/qr")
@Tag(
        name = "心永二维码URL设置",
        description = "将本方提供的“获取二维码字符串 API 地址”提交至心永开放平台后台，用于平台侧拉起生成二维码。"
)
// 如无需鉴权可删除下一行；若需要鉴权，这里以标准 Authorization 头为例
//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class QrUrlController {

    @Autowired
    private HTTPUtils httpUtils;

    /**
     * 心永平台根地址，可直接使用默认值；如环境不同可在配置里覆盖
     */
//    @Value("${heart.api.base-url:https://open.heart-forever.com}")
//    @Schema(description = "心永平台根地址（配置项）", example = "https://open.heart-forever.com")
    private static  final String heartBaseUrl="https://open.heart-forever.com";

    /**
     * 从配置注入 access_token（建议定时刷新）
     * application.yml:
     * heart:
     *   api:
     *     access-token: xxxxxx
     */
//    @Value("${heart.api.access-token}")
//    @Hidden // 配置字段一般不在对外文档展示
    private  static final String accessToken="eyJ0b2tlblR5cGUiOiJhcGkiLCJyYW5kb21LZXkiOiJmNWI3MDk4MmZjNmZjYWY0NmViYmY5MWI5NjdiZjA0ZCIsImV4cCI6MTc2MTgzMzMyNSwiYXBwaWQiOiJicF9lempzaWVqcnppb2p3aWVvIn0=";

    private static final String SET_QR_URL_PATH = "/api/ext/qrUrl";

    /**
     * 设置「二维码URL」——把你方提供的获取二维码字符串的API地址提交到心永后台
     */
    @Operation(
            summary = "设置心永平台二维码URL",
            description = """
                    调用心永开放平台接口 **/api/ext/qrUrl**，在请求头中携带 `access_token`，请求体包含要上报的 `url`。\
                    成功后平台将使用该地址获取二维码字符串以供后续业务使用。\
                    说明：`access_token` 建议通过你方服务定时刷新并配置注入。
                    """
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "设置成功（或平台返回 code=0）",
                    content = @Content(
                            mediaType = "application/json",
                            examples = @ExampleObject(
                                    name = "成功示例",
                                    value = """
                                            {
                                              "code": 0,
                                              "msg": "设置成功",
                                              "data": {
                                                "code": 0,
                                                "msg": "ok"
                                              }
                                            }
                                            """
                            )
                    )
            ),
            @ApiResponse(
                    responseCode = "400",
                    description = "请求参数错误（如 url 为空）",
                    content = @Content(
                            mediaType = "application/json",
                            examples = @ExampleObject(
                                    value = """
                                            {
                                              "code": 400,
                                              "msg": "url不能为空",
                                              "data": null
                                            }
                                            """
                            )
                    )
            ),
            @ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误或上游接口异常",
                    content = @Content(
                            mediaType = "application/json",
                            examples = @ExampleObject(
                                    value = """
                                            {
                                              "code": 500,
                                              "msg": "心永接口返回失败",
                                              "data": { "code": -1, "msg": "invalid token" }
                                            }
                                            """
                            )
                    )
            )
    })
    @RequestBody(
            required = true,
            description = "二维码 URL 上报请求体",
            content = @Content(
                    schema = @Schema(implementation = QrUrlSetReq.class),
                    examples = {
                            @ExampleObject(
                                    name = "基础示例",
                                    value = """
                                            { "url": "https://your.domain.com/api/qr/gen" }
                                            """
                            )
                    }
            )
    )
    @PostMapping("/url/set")
    public R<JSONObject> setQrUrl(@Valid @RequestBody QrUrlSetReq req) {

        // 请求体
        Map<String, Object> body = new HashMap<>();
        body.put("url", req.getUrl());

        // 请求头
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        // 如工具类未默认设置 Content-Type，可手动放开下一行
        // headers.add(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8");
        headers.add("access_token", accessToken);

        // 调用心永接口
        String url = heartBaseUrl + SET_QR_URL_PATH;
        JSONObject remoteResp = httpUtils.post(url, body, headers);

        // 常见返回结构不明，这里把源响应透出；若有 code/msg 约定，可在此处做判断后返回 ok/failed
        Integer code = remoteResp.getInteger("code");
        String msg = remoteResp.getString("msg");
        if (code != null && code != 0) {
            return R.<JSONObject>failed(remoteResp, msg != null ? msg : "心永接口返回失败");
        }
        return R.ok(remoteResp, msg != null ? msg : "设置成功");
    }

    /**
     * 入参DTO：只需要提交一个可被微信/浏览器访问的获取二维码字符串API地址
     */
    @Schema(name = "QrUrlSetReq", description = "上报给心永的二维码URL请求体")
    public static class QrUrlSetReq {

        @Schema(
                description = "你方提供的获取二维码字符串 API 地址，需对外可访问",
                example = "https://your.domain.com/api/qr/gen"
        )
        @NotBlank(message = "url不能为空")
        private String url;

        public String getUrl() { return url; }
        public void setUrl(String url) { this.url = url; }
    }
}
